//
//  ViewController.swift
//  ActionDemo
//
//  Created by work on 15/03/2018.
//  Copyright © 2018 work. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import Action

enum SharedInput {
    case button(String)
    case barButton
}

class ViewController: UIViewController {

    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!
    @IBOutlet weak var doSomethingLable: UILabel!
    @IBOutlet weak var customBtn2: UIButton!
    @IBOutlet weak var customBtn1: UIButton!
    @IBOutlet weak var showAlert: UIButton!
    
    var disposableBag = DisposeBag()
    
    let sharedAction = Action<SharedInput, String> { input in
        switch input {
        case .barButton: return Observable.just("UIBarButtonItem with 3 seconds delay").delaySubscription(15, scheduler: MainScheduler.instance)
        case .button(let title): return .just("UIButton " + title)
        }
    }

    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupRx()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    private func setupRx(){
        bindShowAlert()
        bindRightBarBtn()
        bindCustomBtn()
    }
    
    private func bindShowAlert(){
        let action = CocoaAction {
            print("Button was pressed, showing an alert and keeping the activity indicator spinning while alert is displayed")
            return Observable.create { [weak self] observer -> Disposable in
                // Demo: show an alert and complete the view's button action once the alert's OK button is pressed
                let alertController = UIAlertController(title: "Hello world", message: "This alert was triggered by a button action", preferredStyle: .alert)
                var ok = UIAlertAction.Action("OK", style: .default)
                ok.rx.action = CocoaAction {
                    print("Alert's OK button was pressed")
                    observer.onCompleted()
                    return .empty()
                }
                alertController.addAction(ok)
                self?.present(alertController, animated: true, completion: nil)
                
                return Disposables.create()
            }
        }
        showAlert.rx.action = action
    }
    
    private func bindRightBarBtn(){
        self.navigationItem.rightBarButtonItem?.rx.action = CocoaAction {
            print("Bar button item was pressed, simulating a 2 second action")
            return Observable.empty().delaySubscription(2, scheduler: MainScheduler.instance)
        }
    }
    
    private func bindCustomBtn(){
        Observable.combineLatest(
            showAlert.rx.action!.executing,
            self.navigationItem.rightBarButtonItem!.rx.action!.executing) { a,b in
                // we combine two boolean observable and output one boolean
                return a || b
            }
            .distinctUntilChanged()
            .subscribe(onNext: { [weak self] executing in
                // every time the execution status changes, spin an activity indicator
                self?.doSomethingLable.isHidden = !executing
                if (executing) {
                    self?.activityIndicator.startAnimating()
                }
                else {
                    self?.activityIndicator.stopAnimating()
                }
            })
            .disposed(by: self.disposableBag)
        customBtn1.rx.bind(to: sharedAction, input: .button("Button 1"))
        
        customBtn2.rx.bind(to: sharedAction) { _ in
            return .button("Button 2")
        }
        self.navigationItem.leftBarButtonItem?.rx.bind(to: sharedAction, input: .barButton)
        sharedAction.executing.debounce(0, scheduler: MainScheduler.instance).subscribe(onNext: { [weak self] executing in
            if (executing) {
                self?.activityIndicator.startAnimating()
            }
            else {
                self?.activityIndicator.stopAnimating()
            }
        })
            .disposed(by: self.disposableBag)
        
        sharedAction.elements.subscribe(onNext: { string in
            print(string  + " pressed")
        })
            .disposed(by: self.disposableBag)
    }


}

